<template>
  <el-container v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)">
    <div style="padding: 10px;padding-bottom: 0">
      <div class="report_header" ref="headerHeight">
        <div style="display: flex;align-items: center">
          <div class="report_header_left"></div>
          <div style="width: 800px;display: flex;align-items: center;">
            <div class="report_header_date">
              <el-date-picker
                v-model="query.date"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="queryClick"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <div class="report_header_query">
              <el-select v-model="sysMchName" placeholder="请选择商户" filterable
                         value-key="id" :filter-method="querySysmch" clearable @change="changeSysMch">
                <el-option style="width:300px" v-for="item in mchIdOptions" :key="item.id" :label="item.name"
                           :value="item">
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="sysClick">搜索商户</div>
                </div>
                <div style="height: 40px"></div>
              </el-select>
            </div>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">

            <el-button style="margin-left: 10px;margin-top: 7px;height: 100%" size="small" type="primary"
                       @click="queryClick">查询
            </el-button>
            <ExportList2Excel ref="exportList2Excel"
                              style="margin-left: 10px;margin-top: 7px;height: 32px;padding: 9px 15px"
                              @handleExport="handleExport" v-permission="['financialReport.export']"/>
          </div>
        </div>
        <div style="width: 800px;display: flex;align-items: center;" v-show="queryType == true">
          <!--          这是放隐藏条件的容器-->
        </div>
      </div>
    </div>
    <div class="pd10">
<!--      <el-table :data="orderForm" :height="curHeight" style="width: 100%;" row-key="id" border stripe show-summary :summary-method="summaryMethod"  @sort-change="sortChange">-->
        <el-table :data="orderForm" :height="curHeight" style="width: 100%;" row-key="id" border stripe @sort-change="sortChange">
        <el-table-column :label="item.label" :prop="item.prop" align="center"
                         v-for="(item,index) in labelAndProp" :key="index" sortable="custom"/>
      </el-table>
    </div>
    <el-dialog
      title="双击选择商户"
      :visible.sync="mchTableVisible"
      width="650px"
      v-el-drag-dialog
      append-to-body
      :before-close="mchTableClose">
      <div style="position: relative;">
        <enterprise @mchDouble="mchDouble"></enterprise>
      </div>
    </el-dialog>
    <el-footer class="el-footerBox" style="margin-bottom: auto">
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="pagination"></pagination>
    </el-footer>
  </el-container>
</template>

<script>
    import Pagination from "@/components/Pagination/index";
    import enterprise from "@/components/Enterprise/index";
    import permission from "@/directive/permission";
    import elDragDialog from "@/directive/el-drag-dialog";
    import {mapGetters} from "vuex";
    import {EventBus} from "@/api/eventBus";
    import utils from "@/utils/utils";
    import {list as mchList} from "@/api/enterprise";
    import {detail} from "@/api/reportOrder";
    import {dateFormatter} from "@/filters";
    import ExportList2Excel from "@/components/ExportList2Excel/index";

    export default {
      name: 'financialReport-list',
      components: {ExportList2Excel, Pagination, enterprise},
      directives: {elDragDialog, permission},
      data() {
        return {
          orderForm: [],
          mchTableVisible: false,
          labelAndProp: [
            {
              label: "商户名",
              prop: "name"
            },
            {
              label: "订单日期",
              prop: "createDate"
            },
            {
              label: "完成日期",
              prop: "finishDate"
            },
            {
              label: "结算状态",
              prop: "isDistribution"
            },
            {
              label: "平台结算日期",
              prop: "distributionDate"
            },
            {
              label: "预计送达时间",
              prop: "estimateDate"
            },
            {
              label: "订单号",
              prop: "sn"
            },
            {
              label: "包装费用",
              prop: "packagingFee"
            },
            {
              label: "商家补贴",
              prop: "discount"
            },
            {
              label: "政府补贴",
              prop: "govAmount"
            },
            {
              label: "平台补贴",
              prop: "ptAmount"
            },
            {
              label: "实际付款",
              prop: "amountPaid"
            },
            {
              label: "应付金额",
              prop: "amountPayable"
            },
            {
              label: "商品费用",
              prop: "subPrice"
            },
            {
              label: "服务费用",
              prop: "wxFee"
            },
            {
              label: "订单总额",
              prop: "totalPrice"
            },
            {
              label: "结算金额",
              prop: "distributionAmount"
            },
            {
              label: "平台配送费用",
              prop: "riderFee"
            },
            {
              label: "商家配送费用",
              prop: "freight"
            },
            {
              label: "微信交易单号",
              prop: "tranSn"
            },
            {
              label: "提货方式",
              prop: "shippingMethod"
            },
            {
              label: "订单状态",
              prop: "orderStatus"
            },
            {
              label: "支付状态",
              prop: "paymentStatus"
            },
            {
              label: "收货状态",
              prop: "shippingStatus"
            },

            //
            // {
            //   label: "订单类型",
            //   prop: "orderNum"
            // },
            //  {
            //   label: "服务费用",
            //   prop: "fee"
            // },  {
            //   label: "手续费用",
            //   prop: "orderStatus"
            // }
          ],
          pageNum: 1,
          pageSize: 20,
          total: 0,
          curHeight: null,
          sysMchName: '',
          enterpriseId: '',
          queryType: true,
          mchIdOptions: [],
          orderStatus: 0, // 订单状态
          query: {
            date: [],
            orderSn: '',

            memberId: '',
            phone: '',
            productId: ''
          },
          keyword: {
            date: [],
            orderSn: '',
            memberId: '',
            phone: '',
            productId: ''
          },
          pickerOptions: {//时间快捷选择
            shortcuts: [{
              text: '今天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                picker.$emit('pick', [start, end])
              }
            },{
              text: '昨天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24)
                end.setTime(end.getTime() - 3600 * 1000 * 24)
                picker.$emit('pick', [start, end])
              }
            }, {
              text: '最近一周',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            }, {
              text: '本月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setDate(1)
                picker.$emit('pick', [start, end])
              }
            },{
              text: '最近一个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              }
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                picker.$emit('pick', [start, end])
              }
            }]
          },
          loading:false
        }
      },

      computed: {
        ...mapGetters([
          'mchId'
        ])
      },
      created() {
        var _this = this
        this.loadMch('')
        this.loadOrder()
        EventBus.$on('order-view', res => { // 监听订单删除
          // 更新列表数组
          for (var i = 0; i < _this.orderForm.length; i++) {
            if (_this.orderForm[i].id == res.id) {
              _this.$set(this.orderForm, i, res)
            }
          }
        })
      },
      mounted() {
        this.comeIn()
        // this.beforeMount()
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            if (!_this.queryType) {
              _this.curHeight = h - 311//减去页面上固定高度height
            } else {
              _this.curHeight = h - 224//减去页面上固定高度height
            }
          })()
        }
      },
      methods: {
        mchTableClose(){
          this.mchTableVisible=false
        },
        sysClick(){
          this.mchTableVisible=true
        },
        mchDouble(data){
          this.sysMchName=data.name
          this.enterpriseId=data.enterpriseId
          this.mchTableVisible=false
          this.loadOrder()
        },
        changeSysMch(data){
          if (!utils.isNull(data)){
            this.sysMchName=data.name
            this.enterpriseId=data.id

          }else{
            this.sysMchName=''
            this.enterpriseId=''
          }

        },
        querySysmch(query){
          this.loadMch(query)
        },
        loadMch(query){
          mchList({
            name:query
          }).then(res=>{
            this.mchIdOptions=res.data.data
          })
        },

        setCurHeight(){
          var _this = this
          var h = document.documentElement.clientHeight || document.body.clientHeight
          if (_this.queryType === false) {
            _this.curHeight = h - 311//减去页面上固定高度height
          } else {
            _this.curHeight = h - 224//减去页面上固定高度height
          }
        },
        comeIn() {
          setTimeout(()=>{
            this.setCurHeight()
          },1000)
          var h = document.documentElement.clientHeight || document.body.clientHeight
          this.curHeight = h - 225//减去页面上固定高度height
        },
        loadOrder(pageNum,pageSize) {
          // const loading = this.$loading({
          //   fullscreen:false,
          //   lock: true,
          //   text: '加载中，请稍后，不用刷新页面',
          //   spinner: 'el-icon-loading',
          //   background: 'rgba(0, 0, 0, 0.7)'
          // });
          this.loading = true
          var _this = this
          let params = new URLSearchParams()
          params.append('pageNum', pageNum||_this.pageNum)
          params.append('pageSize', pageSize||_this.pageSize)
          params.append('status', _this.orderStatus)
          params.append('sortField', _this.sortField||'')
          params.append('direction', _this.direction||'')
          if(!utils.isNull(_this.enterpriseId)){
            params.append('enterpriseId',_this.enterpriseId)
          }
          if(this.keyword.date != null && this.keyword.date.length != 0){
            params.append('startDate', this.keyword.date[0])
            params.append('endDate', this.keyword.date[1])
          }else{
            params.append('startDate', '2021-01-01')
            params.append('endDate', dateFormatter(new Date().getTime()))
          }
          detail(params).then(res => {
            res.data.data = res.data.data.map(e=>{
              // console.log(dateFormatter(e.createDate))

              return{
                ...e,
                totalPrice: (e.subPrice+e.packagingFee+e.freight).toFixed(2),
                packagingFee: e.packagingFee.toFixed(2),
                discount: e.discount.toFixed(2),
                govAmount: e.govAmount.toFixed(2),
                ptAmount: e.ptAmount.toFixed(2),
                amountPaid: e.amountPaid.toFixed(2),
                amountPayable: e.amountPayable.toFixed(2),
                subPrice: e.subPrice.toFixed(2),
                distributionAmount: e.distributionAmount.toFixed(2),
                ignoreColumn: e.ignoreColumn.toFixed(2),
                riderFee: e.riderFee.toFixed(2),
                freight: e.freight.toFixed(2),
                createDate:dateFormatter(e.createDate),
                distributionDate:dateFormatter(e.distributionDate),
                estimateDate:dateFormatter(e.estimateDate),
                finishDate:dateFormatter(e.finishDate),
                isDistribution:e.isDistribution?'已结算':'未结算',
              }
            })
            if(pageNum!==undefined&&pageSize!==undefined){
              _this.downLoad(res.data.data)
              this.loading = false
              // loading.close();
              return
            }
            _this.orderForm = res.data.data
            _this.total = res.data.total
            // loading.close();
            this.loading = false
          }).catch(error => {
            // loading.close();
            this.loading = false
            console.log('error!!')
          })
        },

        queryClick() {
          this.keyword = this.query
          this.pageNum = 1
          this.loadOrder()
        },
        downLoad(outputData){
          let columnCount = this.labelAndProp.length
          let rowCount = outputData.length
          // let filename = `${this.query.date[0]}~${this.query.date[1]}餐巴账单汇总`
          let filename = this.query.date.length?`${this.query.date[0]}~${this.query.date[1]}餐巴账单汇总`:'餐巴账单汇总'
          let multiHeader = [[filename, ...new Array(columnCount - 1).fill('')]];
          // let merges = [`A1:${String.fromCharCode(columnCount + 64)}1`,`A${rowCount+3}:B${rowCount+3}`]; //暂不处理超过24列的情况
          let tHeader = this.labelAndProp.map(e => e.label);
          let filterVal = this.labelAndProp.map(e => e.prop);
          let countRow = outputData.reduce((acc,cur)=>{
            filterVal.forEach(e=>{
              let curVal = Number(cur[e]||0)*100
              if(curVal === curVal){
                acc[e] = ((Number(acc[e]||0)*100 + curVal)/100).toFixed(2)
              }else{
                acc[e] = ''
              }
            })
            return acc
          },{})
          countRow[filterVal[0]] = "合计"
          let list = outputData.concat(countRow);
          this.$refs.exportList2Excel.handleDownload(
            {
              // multiHeader: multiHeader,
              // merges: merges,
              tHeader: tHeader,
              filterVal: filterVal,
              list: list,
              filename: filename
            }
          )
        },
        async handleExport() {
          //TODO 最长导出时间间隔？
          // if(!this.query.date.length){
          //   this.$message({
          //     message: '请选择日期后再导出',
          //     type: 'warning'
          //   });
          //   return
          // }
          //TODO 再次全量查询所需下载的数据
          this.loadOrder(1,100000)
        },
        summaryMethod({columns,data }){
          return new Array(columns.length).fill(1)
        },
        sortChange(column) {
          this.sortField = column.prop;
          if (column.order === 'ascending') {
            this.direction = 'asc'
          } else {
            this.direction = 'desc'
          }
          this.loadOrder()
        },
        pagination({page, limit}) {
          this.pageNum = page
          this.pageSize = limit
          this.loadOrder()
        }
      }
    }
</script>

<style scoped>
  .details_card {
    overflow: auto;
    padding-left: 20px;
    padding-right: 20px;
    box-sizing: border-box;
    border: 1px solid #f2f2f2;
    border-radius: 4px;
  }

  .elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }

  .details_card:hover {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
  }

  .el-input__inner {
    width: 100% !important;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/ .el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
    flex-direction: column;
  }
  /deep/.el-dialog__header{
    border-bottom: 1px solid rgba(0,0,0,0.1);
  }
  .report_header_left {
    width: 5px;
    height: 46px;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }

  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
</style>
